<template>
  <div id="articleAdd">
    <el-form ref="form" :model="form" label-width="160px" :rules="rules">
      <!-- 标题 -->
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <!-- 标签分类 -->
      <el-form-item label="标签分类" prop="category_id">
        <el-select v-model="form.category_id" placeholder="请选择活动区域">
          <el-option :label="item.name" :value="item.id" v-for="item of category" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <!-- 热门设置 -->
      <el-form-item label="热门">
        <el-switch
          v-model="form.hot"
          :active-value="1"
          :inactive-value="0"
          active-color="#02538C"
          inactive-color="#B9B9B9"
        />
      </el-form-item>
      <!-- 上传缩略图 -->
      <el-form-item label="缩略图">
        <el-upload action="#" list-type="picture-card" :auto-upload="false"
        :on-change="handleFileChange">
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{file}">
            <img class="el-upload-list__item-thumbnail" :src="file.url" alt />
            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                <i class="el-icon-zoom-in"></i>
              </span>
            </span>
          </div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt />
        </el-dialog>
      </el-form-item>
      <!-- 内容区 -->
      <el-form-item label="内容">
        <div id="editor" ref="editorElm"></div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleArticleAdd('form')">发表</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import E from "wangeditor";
export default {
  data() {
    return {
      form: {
        title: "",
        content: "",
        hot: 0,
        time: 0,
        category_id: null,
        category_name: "",
        description_image_path:''
      },
      // 默认不显示图片预览
      dialogVisible: false,
      //图片预览地址
      dialogImageUrl: "",
      rules: {
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          { min: 0, max: 25, message: "长度在 0 到 25 个字符", trigger: "blur" }
        ],
        category_id: [
          { required: true, message: "请选择分类标签", trigger: "change" }
        ]
      },
      editor: null,
      editorContent: "",
      category: []
    };
  },
  methods: {
     handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 将图片数据放入 from 中
    handleFileChange(file){
      this.form.description_image_path = file.raw
    },
    // 富文本设置
    handleOpen() {
      // 将原先的富文本编辑器清空，防止嵌套 BUG
      this.$refs.editorElm.innerHTML = "";
      // 实例化富文本编辑器
      this.editor = new E("#editor");
      // 当富文本器中的内容发生改变时，把内容赋值到表单数据中
      this.editor.customConfig.onchange = html => {
        console.log(html);
        this.form.content = html;
      };
      this.editor.create();
    },
    // 请求分类标签并设置到分类选择表单中
    handleCategory() {
      this.$http.get("api/category").then(res => {
        this.category = res.data;
      });
    },
    handleArticleAdd(formName) {
      // 判断必填项是否填写
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 设置发表时间
          this.form.time = Date.now();
          // 将分类标签填入
          this.category.forEach(e => {
            if (e.id === this.form.category_id) {
              this.form.category_name = e.name;
              return;
            }
          });
          let form = new FormData();
          for(let i in this.form){
            form.append(i,this.form[i])
          } 
          console.log(form);
          // 发送请求
          this.$http({
            url: "api/articleAdd",
            method: "post",
            data: form
          }).then(res => {
            if (res.data.code === 1) {
              this.$message({
                message: res.data.msg,
                type: "success"
              });
              // 延时跳转
              setTimeout(()=>{
                this.$router.push('/article');
              },1000)
            } else {
              this.$message({
                message: res.data.msg,
                type: "warning"
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  },
  mounted() {
    this.handleOpen();
    this.handleCategory();
  }
};
</script>
<style lang='less'>
#articleAdd {
  padding: 40px 100px 0 0;
  .el-form-item__label {
    font-size: 16px;
  }
}

// 图片上传样式
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>